package com.fzj.example.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * ClassName: URLDemo
 * date: 2019/11/19 11:24
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class URLDemo {
    public static void main(String[] args) {
        URL  url;
        //String url0="https://www.bonree.com/user-login.html";
        String url0="http://devtest.ibr.cc:30020";
        try{
            url=new URL(url0);
            //getContent内部调用了url.openConnection();
            //System.out.println("url.getContent()    "+url.getContent());
            //编码由url服务端决定的，url.getPort,没带默认是-1，所以写代码应该用url.getDefaultPort()和url.getPort一起判断
/*            int port;
            if((port=url.getPort())==-1){
                port=url.getDefaultPort();
            }*/
/*            URLConnection urlConnection=url.openConnection();
            InputStreamReader inputStreamReader =new InputStreamReader(urlConnection.getInputStream(),"gb2312");
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            char[] chars=new char[1024];
            int len;
            while((len=inputStreamReader.read(chars))!=-1){
                System.out.println(new String(chars,0,len));
            }
            inputStreamReader.close();*/
            URLConnection urlConnection=url.openConnection();
            InputStream inputStream =urlConnection.getInputStream();
            byte[] bytes=new byte[1024];
            int len;
            while((len=inputStream.read(bytes))!=-1){
                System.out.println(new String(bytes,0,len,"utf-8"));
            }
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
